package in.muton.edushare.wicket.converters.choicerenderers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

public class GenericRenderer<E> implements IChoiceRenderer<String> {
	
	public IModel<String> getModel(){
		return new PropertyModel<String>(this,"selectedValue"); 
	}
	
	public Object getDisplayValue(String arg0) {
		return arg0;
	}

	public String getIdValue(String arg0, int arg1) {
		return Integer.toString(arg1);
	}
	
	public GenericRenderer(HashMap<String, E> options, E initVal){
		String[] keyArr = new String[options.size()];
		keyArr = options.keySet().toArray(keyArr);
		keyList = Arrays.asList(keyArr);
		optionMap = options;
		selectedValue = initVal;
	}
	
	public List<String> getOptions(){
		return keyList;
	}
	
	public String getSelectedValue(){
		for(String k:keyList){
			if(optionMap.get(k).equals(selectedValue)){
				return k;
			}
		}
		return null;
	}
	
	public void setSelectedValue(String str){
		selectedValue = optionMap.get(str);
	}
	
	public E getSelection(){
		return selectedValue;
	}
	
	public void sort(boolean ascending){
		Collections.sort(keyList);
		if(!ascending)
			Collections.reverse(keyList);
	}
	
	private List<String> keyList = new ArrayList<String>();
	private HashMap<String, E> optionMap;
	private E selectedValue;	
	private static final long serialVersionUID = 2514504969662857930L;
}
